﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using log4net;

namespace Umbrella.Whs.Service.Activities
{

    public sealed class WriteToLog : SafeCodeActivity
    {
        public enum LogLevel
        {
            Info,       // default
            Debug,
            Warning,
            Error
        }

        public InArgument<string> Logger { get; set; }

        public InArgument<LogLevel> Level { get; set; }

        [RequiredArgument]
        public InArgument<string> Message { get; set; }

        public InArgument<Exception> Error { get; set; }


        protected override void ExecuteSafe(CodeActivityContext context)
        {
            // gather logger name
            var logger = context.GetValue(this.Logger);

            if ((this.Logger == null) || string.IsNullOrEmpty(logger))
                logger = ("WF#" + context.WorkflowInstanceId.ToString("N"));

            // gather misc
            var level = context.GetValue(this.Level);
            var msg = context.GetValue(this.Message);
            var err = context.GetValue(this.Error);

            var log = LogManager.GetLogger(logger);

            // validate level
            switch (level)
            {
                case LogLevel.Debug:
                    if (log.IsDebugEnabled)
                    {
                        if (err != null)
                            log.Debug(msg, err);
                        else
                            log.Debug(msg);
                    }

                    break;

                case LogLevel.Info:
                    if (log.IsInfoEnabled)
                    {
                        if (err != null)
                            log.Info(msg, err);
                        else
                            log.Info(msg);
                    }

                    break;

                case LogLevel.Warning:
                    if (log.IsWarnEnabled)
                    {
                        if (err != null)
                            log.Warn(msg, err);
                        else
                            log.Warn(msg);
                    }

                    break;

                case LogLevel.Error:
                    if (log.IsErrorEnabled)
                    {
                        if (err != null)
                            log.Error(msg, err);
                        else
                            log.Error(msg);
                    }

                    break;

                default:
                    throw new ArgumentOutOfRangeException("unknown log level: " + level);
            }
        }
    }
}
